<template>
  <div class="user">
    <!--        面包屑导航-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!--        卡片栏-->
    <el-card>
      <el-row :gutter="20">
        <el-col :span="8">
          <!--            搜索框-->
          <el-input
            placeholder="请输入内容"
            class="input-with-select"
            v-model="userInfo.query"
            clearable
            @clear="getUsers"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUsers"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addButton">添加用户</el-button>
        </el-col>
      </el-row>
      <!--            用户信息栏-->
      <el-table :data="userList" border stripe>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="shut">
            <!--                    开关-->
            <el-switch
              v-model="shut.row.mg_state"
              @change="statusChange(shut.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="shut">
            <!--                    编辑按钮-->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="(editShutVisible = true), (editMsg = shut.row)"
            ></el-button>
            <!--                    删除按钮-->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="deleteUser(shut.row)"
            >
            </el-button>
            <el-tooltip
              effect="dark"
              content="分配角色"
              placement="top"
              :enterable="false"
            >
              <!--                    分配角色按钮-->
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="changeRole(shut.row)"
              >
              </el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!--            分页栏-->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="userInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="userInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
    <!--        添加用户的弹出框-->
    <el-dialog :title="title" :visible.sync="shutVisible" width="50%">
      <!--            添加用户的表单-->
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="70px"
      >
        <!--                表单内容区-->
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="shutVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser()">确 定</el-button>
      </span>
    </el-dialog>
    <!--        编辑用户弹出框-->
    <el-dialog :title="title" :visible.sync="editShutVisible" width="50%">
      <!--            编辑用户的表单-->
      <el-form
        :model="editForm"
        :rules="editFormRules"
        ref="editFormRef"
        label-width="70px"
      >
        <!--                表单内容区-->
        <el-form-item label="用户ID" prop="id">
          <el-input v-model="editForm.id"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editShutVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUser(editMsg)">确 定</el-button>
      </span>
    </el-dialog>
    <!--        分配角色弹出框-->
    <el-dialog :title="title" 
    :visible.sync="roleShutVisible" 
    width="40%"
    @close="selectList = ''">
      <!--            分配角色的表单-->
      <el-form
        :model="roleForm"
        :rules="roleFormRules"
        ref="roleFormRef"
        label-width="70px"
        class="left"
      >
        <div>
          <p>当前用户: {{ roleMsg.username }}</p>
          <p>当前角色: {{ roleMsg.role_name }}</p>
          <p>
            分配新角色:
            <el-select v-model="selectList" placeholder="请选择">
              <el-option
                v-for="item in rolesList"
                :key="item.id"
                :label="item.roleName"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </p>
        </div>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="roleShutVisible = false">取 消</el-button>
        <el-button type="primary" @click="roleUser(roleMsg)">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "User",
  data() {
    var checkEmail = (rule, value, callback) => {
      const res = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$|^$/;
      if (res.test(value)) {
        return callback();
      }
      callback(new Error("请输入合法邮箱"));
    };
    var checkMobil = (rule, value, callback) => {
      const res = /^(13[0-9]|14[5|7]|15[0|1|2|3|4|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9]|17[0-9])\d{8}$|^$/;
      if (res.test(value)) {
        return callback();
      }
      callback(new Error("请输入合法手机号"));
    };
    return {
      userInfo: {
        query: "",
        pagenum: 1,
        pagesize: 2,
      },
      title: "",
      userList: [],
      total: 0,
      shutVisible: false,
      editShutVisible: false,
      roleShutVisible: false,
      editMsg: {},
      roleMsg: {},
      rolesList: [],
      selectList:'',
      addForm: {
        username: "",
        password: "",
        email: "",
        mobile: "",
      },
      addFormRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 3,
            max: 10,
            message: "长度在 3 到 10 个字符",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 6,
            max: 16,
            message: "长度在 6 到 16 个字符",
            trigger: "blur",
          },
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" },
        ],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { validator: checkMobil, trigger: "blur" },
        ],
      },
      editForm: {
        id: "",
        email: "",
        mobile: "",
      },
      editFormRules: {
        id: [
          { required: true, message: "请输入修改后的ID", trigger: "blur" },
          { min: 1, max: 4, message: "长度在 1 到 4 个字符", trigger: "blur" },
        ],
        email: [{ validator: checkEmail, trigger: "blur" }],
        mobile: [{ validator: checkMobil, trigger: "blur" }],
      },
      roleForm: {
        id: "",
        rid: "",
      },
      roleFormRules: {
        rid: [
          { required: true, message: "请输入修改后的角色ID", trigger: "blur" },
          { min: 1, max: 4, message: "长度在 1 到 4 个字符", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getUsers();
  },
  methods: {
    getUsers() {
      this.$http
        .get("users", {
          params: this.userInfo,
        })
        .then((res) => {
          if (res.data.meta.status !== 200)
            return this.$message.error("数据获取失败");
          this.userList = res.data.data.users;
          this.total = res.data.data.total;
        });
    },
    handleSizeChange(newSize) {
      this.userInfo.pagesize = newSize;
      this.getUsers();
    },
    handleCurrentChange(newPage) {
      this.userInfo.pagenum = newPage;
      this.getUsers();
    },
    statusChange(userStatus) {
      this.$http
        .put(`users/${userStatus.id}/state/${userStatus.mg_state}`)
        .then((res) => {
          if (res.data.meta.status !== 200) {
            userStatus.mg_state = !userStatus.mg_state;
            return this.$message.error("更新用户状态失败");
          }
          this.$message.success("更新用户状态成功");
        });
    },
    deleteUser(data) {
      this.$http.delete(`users/${data.id}`).then((res) => {
        const ress = res.data.meta;
        if (ress.status !== 200) return this.$message.error(ress.msg);
        this.$message.success(ress.msg);
        this.getUsers();
      });
    },
    addUser() {
      this.$refs.addFormRef.validate((res) => {
        if (!res) return this.$message.error("添加失败，请检查格式");
        this.$http.post("users", this.addForm).then((res) => {
          const ress = res.data.meta;
          if (ress.status !== 201) return this.$message.error(ress.msg);
          this.$message.success(ress.msg);
          this.getUsers();
          this.shutVisible = false;
        });
      });
    },
    addButton() {
      this.shutVisible = true;
      this.title = "添加用户";
    },
    editUser(data) {
      this.title = "编辑用户";
      this.$refs.editFormRef.validate((res) => {
        if (!res) return this.$message.error("编辑失败，请检查格式");
        this.$http.put(`users/${data.id}`, this.editForm).then((res) => {
          const ress = res.data.meta;
          if (ress.status !== 200) return this.$message.error(ress.msg);
          this.$message.success(ress.msg);
          this.getUsers();
          this.editShutVisible = false;
        });
      });
    },
    /* 展示分配角色的对话框 */
    async changeRole(data) {
      this.roleMsg = data;
      const { data: res } = await this.$http.get("roles");
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.rolesList = res.data;
      this.roleShutVisible = true;
    },
    roleUser(data) {
      this.title = "分配用户角色";
      if(!this.selectList) return this.$message.error('请选择分配的角色')
        this.$http.put(`users/${data.id}/role`, {
            rid:this.selectList
            }).then((res) => {
          const ress = res.data.meta;
          if (ress.status !== 200) return this.$message.error(ress.msg);
          this.$message.success(ress.msg);
          this.getUsers();
          this.roleShutVisible = false;
        });
    },
  },
};
</script>

<style scoped>
.user {
  text-align: center;
}
.left {
  text-align: left;
  padding: 10px 130px;
  font-size: 14px;
}
</style>
